package com.jilian.mydemo.modul.order.ui;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.contrarywind.view.WheelView;
import com.jilian.mydemo.Constant;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.base.BaseEventMsg;
import com.jilian.mydemo.common.dto.FinishImgDto;
import com.jilian.mydemo.common.dto.OrderDto;
import com.jilian.mydemo.common.dto.ParamsDto;
import com.jilian.mydemo.common.dto.ParamsListDto;
import com.jilian.mydemo.common.dto.ProductDetailDto;
import com.jilian.mydemo.dialog.nicedialog.BaseNiceDialog;
import com.jilian.mydemo.dialog.nicedialog.NiceDialog;
import com.jilian.mydemo.dialog.nicedialog.ViewConvertListener;
import com.jilian.mydemo.dialog.nicedialog.ViewHolder;
import com.jilian.mydemo.event.RxBus;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.modul.my.adapter.InputServiceDataAdapter;
import com.jilian.mydemo.modul.my.ui.SettingActivity;
import com.jilian.mydemo.modul.order.adapter.SelectServiceWheelAdapter;
import com.jilian.mydemo.modul.order.viewmodel.OrderViewModel;
import com.jilian.mydemo.modul.shop.ui.AccessoriesShopActivity;
import com.jilian.mydemo.modul.user.activity.LoginActivity;
import com.jilian.mydemo.utils.DateUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.PinziDialogUtils;
import com.jilian.mydemo.utils.RxTimerUtil;
import com.jilian.mydemo.utils.SPUtil;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.views.CustomLinearLayoutManager;
import com.jilian.mydemo.views.MyRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;


/**
 * 填写服务产品想信息
 */
public class InputServiceDataActivity extends BaseActivity implements CustomItemClickListener, InputServiceDataAdapter.InputServiceListener {
    private MyRecyclerView recyclerView;
    private InputServiceDataAdapter adapter;
    private List<FinishImgDto> mDatas;
    private CustomLinearLayoutManager linearLayoutManager;
    private TextView tvOk;
    private OrderViewModel orderViewModel;
    private OrderDto orderDto;
    private String orderId;


    @Override
    protected void createViewModel() {
        orderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_inputservicedata;
    }

    @Override
    public void initView() {
        setNormalTitle("服务产品信息填写", v -> finish());
        String data = getIntent().getStringExtra("data");
        orderId = getIntent().getStringExtra("orderId");
        orderDto = (OrderDto) getIntent().getSerializableExtra("order");
        tvOk = (TextView) findViewById(R.id.tv_ok);
        mDatas = JSONObject.parseArray(data, FinishImgDto.class);
        recyclerView = (MyRecyclerView) findViewById(R.id.recyclerView);
        linearLayoutManager = new CustomLinearLayoutManager(this);
        linearLayoutManager.setScrollEnabled(false);
        recyclerView.setLayoutManager(linearLayoutManager);
        for (int i = 0; i < mDatas.size(); i++) {
            mDatas.get(i).setLists(new ArrayList<ProductDetailDto>());
        }
        adapter = new InputServiceDataAdapter(this, mDatas, this, this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void initData() {
        initParam();
        initCustomTimePicker();
    }

    /**
     * 初始化参数
     */
    private void initParam() {
        orderViewModel.initParams();
        orderViewModel.getParamsliveData().observe(this, new Observer<BaseDto<ParamsListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<ParamsListDto> paramsListDtoBaseDto) {
                if (paramsListDtoBaseDto.isSuccess()) {
                    fixPlaces = paramsListDtoBaseDto.getData().getFixPlaces();
                    fixPipes = paramsListDtoBaseDto.getData().getFixPipes();
                    fixFrame = paramsListDtoBaseDto.getData().getFixFrame();
                    purposes = paramsListDtoBaseDto.getData().getPurposes();

                }
            }
        });
    }

    @Override
    public void initListener() {
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmptyUtils.isNotEmpty(adapter.getDatas())) {
                    ToastUitl.showImageToastTips("没有服务产品");
                    return;
                }
                for (int i = 0; i < adapter.getDatas().size(); i++) {
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getSerialNum())) {
                        ToastUitl.showImageToastTips("请填写机身编码");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getRepairNum())) {
                        ToastUitl.showImageToastTips("请填写报修卡号");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getLvXinCode())) {
                        ToastUitl.showImageToastTips("请填写滤芯编号");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getProduceTime())) {
                        ToastUitl.showImageToastTips("请填写生产日期");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getOldWaterGage())) {
                        ToastUitl.showImageToastTips("请填写原水压");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getNewWaterGage())) {
                        ToastUitl.showImageToastTips("请填写新水压");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getFixPlace())) {
                        ToastUitl.showImageToastTips("请选择安装位置");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getFixPipe())) {
                        ToastUitl.showImageToastTips("请选择安装管路");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getFixFrame())) {
                        ToastUitl.showImageToastTips("请选择安装结构");
                        return;

                    }
                    if (TextUtils.isEmpty(adapter.getDatas().get(i).getPurpose())) {
                        ToastUitl.showImageToastTips("请选择用途");
                        return;

                    }
                }
                showSaveDialog();


            }
        });
        RxBus.getInstance().toObservable().map(
                new io.reactivex.functions.Function<Object, BaseEventMsg>() {
                    @Override
                    public BaseEventMsg apply(Object o) throws Exception {
                        return (BaseEventMsg) o;
                    }
                }).subscribe(new io.reactivex.functions.Consumer<BaseEventMsg>() {
            @Override
            public void accept(BaseEventMsg o) throws Exception {
                if (o != null && o.getSelectGoodDto() != null) {
                    mDatas.get(position).getLists().addAll(o.getSelectGoodDto().getDetailDtoList());
                    adapter.notifyDataSetChanged();
                }

            }
        });
    }

    /**
     * 退出登录对话框
     */
    private void showSaveDialog() {
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        tvTitle.setText("提交确认");
        tvContent.setText("该服务产品信息提交后，里面的数据内容将无法再做修改，是否确认提交？");
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finshOrder();
            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }


    private void finshOrder() {
        showLoadingDialog();
        orderViewModel.finishOrder(getIntent().getStringExtra("orderId"), adapter.getDatas());
        orderViewModel.getFinishliveData().observe(this, new Observer<BaseDto>() {
            @Override
            public void onChanged(@Nullable BaseDto baseDto) {
                hideLoadingDialog();
                if (baseDto.isSuccess()) {
                    ToastUitl.showImageToastTips("提交成功");
                    Intent intent = new Intent(InputServiceDataActivity.this, ThreeOrderDetaiCommitelActivity.class);
                    intent.putExtra("order", orderDto);
                    intent.putExtra("orderId", orderId);
                    startActivity(intent);
                    MyApplication.clearSpecifyActivities(new Class[]{FinishOrderActivity.class,});
                    MyApplication.clearSpecifyActivities(new Class[]{ThreeOrderDetailActivity.class});
                    finish();
                } else {
                    ToastUitl.showImageToastTips(baseDto.getMsg());
                }
            }
        });
    }

    private int position;

    @Override
    public void onItemClick(View view, int position) {

    }

    /**
     * 添加设备
     *
     * @param position
     */
    @Override
    public void addEq(int position) {
        this.position = position;
        Intent intent = new Intent(this, AccessoriesShopActivity.class);
        intent.putExtra("param", 2);
        startActivity(intent);

    }

    /**
     * 安装位置
     */
    private List<ParamsDto> fixPlaces;
    /**
     * 安装管路
     */
    private List<ParamsDto> fixPipes;
    /**
     * 安装结构
     */
    private List<ParamsDto> fixFrame;
    /**
     * 用途
     */
    private List<ParamsDto> purposes;

    /**
     * 安装位置
     *
     * @param position
     */
    @Override
    public void etInstallationPosition(int position) {
        if (!EmptyUtils.isNotEmpty(fixPlaces)) {
            return;
        }
        showDialog(position, fixPlaces, 1);

    }

    /**
     * 安装管路
     *
     * @param position
     */
    @Override
    public void etInstallationPiping(int position) {
        if (!EmptyUtils.isNotEmpty(fixPipes)) {
            return;
        }
        showDialog(position, fixPipes, 2);

    }

    /**
     * 安装结构
     *
     * @param position
     */
    @Override
    public void etInstallationStructure(int position) {
        if (!EmptyUtils.isNotEmpty(fixFrame)) {
            return;
        }
        showDialog(position, fixFrame, 3);
    }

    /**
     * 安装用途
     *
     * @param position
     */
    @Override
    public void etUse(int position) {
        if (!EmptyUtils.isNotEmpty(purposes)) {
            return;
        }
        showDialog(position, purposes, 4);
    }

    TimePickerView pvCustomTime;
    /**
     * 选择生产日期
     *
     * @param position
     */
    private int selectPosition;//日期选择

    @Override
    public void etProductDate(int position) {
        this.selectPosition = position;
        pvCustomTime.show();
    }

    /**
     * 初始化时间数据
     */
    private void initCustomTimePicker() {
        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1918, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 01, 01);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                mDatas.get(selectPosition).setProduceTime(DateUtil.dateToString(DateUtil.DATE_FORMAT_, date) + " 00:00:00");
                adapter.notifyDataSetChanged();

            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, selectedDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        final TextView tvCancel = (TextView) v.findViewById(R.id.tv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setContentTextSize(18)
                //各个部分是否显示
                .setType(new boolean[]{true, true, true, false, false, false})
                //时间格式
                .setLabel("", "", "", ":00", "分", "秒")
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(40, 0, -40, 0, 0, -0)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFFe0e0e0)
                .setLineSpacingMultiplier(2f)
                .build();
    }

    /**
     * @param position
     * @param paramsDtos
     * @param type       1.位置 2.安装管路 3.安装结构  4.安装用途
     */
    private void showDialog(int position, List<ParamsDto> paramsDtos, int type) {

        NiceDialog.init()
                .setLayoutId(R.layout.dialog_select_courier)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        dialog.setOutCancel(false);
                        WheelView wheelview = (WheelView) holder.getView(R.id.wheelview);
                        wheelview.setCyclic(false);
                        TextView tvCancel = (TextView) holder.getView(R.id.tv_cancel);
                        TextView tvFinish = (TextView) holder.getView(R.id.tv_finish);


                        TextView tvTitle = (TextView) holder.getView(R.id.tv_title);
                        switch (type) {
                            case 1:
                                tvTitle.setText("请选择安装位置");
                                break;
                            case 2:
                                tvTitle.setText("请选择安装管路");
                                break;
                            case 3:
                                tvTitle.setText("请选择安装结构");
                                break;
                            case 4:
                                tvTitle.setText("请选择安装用图");
                                break;
                        }


                        wheelview.setAdapter(new SelectServiceWheelAdapter(paramsDtos));

                        tvFinish.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                switch (type) {
                                    case 1:
                                        mDatas.get(position).setFixPlace(paramsDtos.get(wheelview.getCurrentItem()).getCode());
                                        mDatas.get(position).setFixPlaceName(paramsDtos.get(wheelview.getCurrentItem()).getValue());
                                        adapter.notifyDataSetChanged();
                                        break;
                                    case 2:
                                        mDatas.get(position).setFixPipe(paramsDtos.get(wheelview.getCurrentItem()).getCode());
                                        mDatas.get(position).setFixPipeName(paramsDtos.get(wheelview.getCurrentItem()).getValue());
                                        adapter.notifyDataSetChanged();

                                        break;
                                    case 3:
                                        mDatas.get(position).setFixFrame(paramsDtos.get(wheelview.getCurrentItem()).getCode());
                                        mDatas.get(position).setFixFrameName(paramsDtos.get(wheelview.getCurrentItem()).getValue());
                                        adapter.notifyDataSetChanged();
                                        break;
                                    case 4:
                                        mDatas.get(position).setPurpose(paramsDtos.get(wheelview.getCurrentItem()).getCode());
                                        mDatas.get(position).setPurposeName(paramsDtos.get(wheelview.getCurrentItem()).getValue());
                                        adapter.notifyDataSetChanged();

                                        break;
                                }

                            }
                        });
                        tvCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                            }
                        });
                        wheelview.setCurrentItem(0);
                    }
                })
                .setShowBottom(true)
                .show(getSupportFragmentManager());
    }


}
